package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import static com.shanxia.codec.Decoder.bytesToIntLittle;
import static com.shanxia.codec.Decoder.intToBytesLittle;

/**
 * S -> C
 * 服务器下发升级文件大小
 */
@Data
public class Cmd1005 extends ProtocolDataBase {

    public static final int MIN_SIZE = 4;

    private int length;             // 文件长度

    public Cmd1005(){
        super.setCmd(1005);
    }

    public static Cmd1005 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd1005 cmd = new Cmd1005();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        cmd.length = bytesToIntLittle(dataField, 0);
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        byte[] data = new byte[MIN_SIZE];
        intToBytesLittle(data, 0, this.length);
        return data;
    }
}
